/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.txweb.result;

import org.slf4j.Logger;
import com.jspx.boot.environment.Environment;
import org.slf4j.LoggerFactory;
import com.jspx.scriptmark.ScriptMark;
import com.jspx.scriptmark.ScriptmarkEnv;
import com.jspx.scriptmark.config.TemplateConfigurable;
import com.jspx.scriptmark.core.ScriptMarkEngine;
import com.jspx.scriptmark.load.FileSource;
import com.jspx.txweb.ActionInvocation;
import com.jspx.txweb.dispatcher.Dispatcher;
import com.jspx.txweb.support.ActionSupport;
import com.jspx.txweb.util.TXWebUtil;
import com.jspx.utils.FileUtil;
import com.jspx.utils.StringUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: chenYuan
 * Date: 12-4-25
 * Time: 下午5:09
 * 将页面执行后的结果保存为文件，文件名使用 变量 saveFile 保存中环境中
 * 文件保存将会直接覆盖，所以是比较危险的，有重要文件最好先备份
 */
public class FileSaveResult  extends ResultSupport {
    private final static Logger log = LoggerFactory.getLogger(FileSaveResult.class);
    private final static TemplateConfigurable configurable = new TemplateConfigurable();
    private static final String defaultEncode = envTemplate.getString(Environment.encode, Environment.defaultEncode);
    private static String templatePath = envTemplate.getString(Environment.templatePath);
    public static final String saveFile = "saveFile";

    static
    {
        configurable.addAutoIncludes(envTemplate.getString(Environment.autoIncludes));
    }

    public FileSaveResult() {

    }

    public void execute(ActionInvocation actionInvocation) throws Exception {
        ActionSupport action = actionInvocation.getActionProxy().getAction();
        HttpServletResponse response = action.getResponse();
        HttpServletRequest request = action.getRequest();

        File f = new File(action.getTemplatePath(),action.getTemplateFile());
        FileSource fileSource = new FileSource(f,action.getTemplateFile(), defaultEncode);
        //如果使用cache 就使用uri

        configurable.setSearchPath(new String[]{action.getTemplatePath(), Dispatcher.getRealPath(), templatePath});
        ScriptMark scriptMark;
        try {
            scriptMark = new ScriptMarkEngine(ScriptmarkEnv.noCache, fileSource, configurable);
        } catch (Exception e) {
            if (debug)
            {
                log.info("TemplateResult file not found:" + f.getAbsolutePath(), e);
                TXWebUtil.errorPrint("TemplateResult file not found:" + f.getAbsolutePath()+ "<BR>"+ e.getMessage(),response,404);
            } else
            {
                TXWebUtil.errorPrint("file not found,不存在的文件",response,404);
            }
            return;
        }
        scriptMark.setRootDirectory(Dispatcher.getRealPath());
        scriptMark.setCurrentPath(action.getTemplatePath());
        if (StringUtil.isNULL(action.getEnv(saveFile)))
        {
            TXWebUtil.print(saveFile + ",保存文件路径没有定义",TXWebUtil.htmlType,response);
            return;
        }

        File saveFileName = new File(action.getEnv(saveFile));
        //输出模板数据
        FileUtil.makeDirectory(saveFileName.getParent());
        Writer  out = new OutputStreamWriter(new FileOutputStream(saveFileName), defaultEncode);
        if (action.isProcess()) {
            Map<String, Object> valueMap = action.getEnv();
            initPageEnvironment(action,valueMap);
            try{
                scriptMark.process(out, valueMap);
            }  finally {
                valueMap.clear();
            }
        }
        out.flush();
        out.close();

    }
}